<template>
  <div class="page-container">
    <TrSearch
      v-model="searchParams"
      :searchShowList="searchShowList"
      @search-back="searchHandle"
    />
    <div class="common-content-wrap mg-tp-16">
      <TrTable
        lazy
        ref="trTable"
        :isNeedInit="false"
        :btnList="btnList"
        :tableColumn="tableColumn"
        :loadFun="loadFun"
        :tableData="tableData"
        :total="totalNum"
        @add="operateHandle($event, 'add')"
        @rowAdd="operateHandle($event, 'rowAdd')"
        @rowDelete="operateHandle($event, 'rowDelete')"
        @rowEdit="operateHandle($event, 'rowEdit')"
      />
    </div>
    <TrEditPopup
      ref="editPopup"
      v-model="isShowEdit"
      :width="460"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      @close="isShowEdit = false"
      @confrim="confrimHandle"
      @select-change="selectChange"
    />
  </div>
</template>

<script>
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrSearch from "@/components/Tr-search/Tr-search.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";

import enumData from "@/utils/enumCode.js";

import {
  getList,
  getChild,
  getLevel,
  add,
  update,
  remove,
} from "@/api/baseCode/organizationalHierarchy.js";

export default {
  name: "organizationalHierarchy",

  components: {
    TrSearch,
    TrTable,
    TrEditPopup,
  },
  computed: {
    checkTitle() {
      return this.currentHandle == "add"
        ? "新增"
        : this.currentHandle == "rowAdd"
        ? "新增子项"
        : "编辑";
    },
  },
  data: () => ({
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "数据隔离",
        type: "radio",
        width: 100,
        value: 0,
        id: "isIsolation",
        list: [
          {
            label: "是",
            value: 1,
          },
          {
            label: "否",
            value: 0,
          },
        ],
        isNeed: false,
      },
      {
        label: "层级名称",
        type: "input",
        width: 100,
        value: "",
        id: "levelName",
      },
      {
        label: "层级代码",
        type: "select",
        width: 100,
        value: "",
        id: "levelCode",
        list: [],
        disabled: false,
      },
      {
        label: "上级层级",
        type: "select",
        width: 100,
        value: "",
        id: "parentId",
        list: [],
        disabled: false,
        isNeed: false,
      },
      {
        label: "层级序列",
        type: "input",
        inputType: "number",
        width: 100,
        value: "",
        id: "sort",
        disabled: true,
      },
    ],
    isShowEdit: false,

    searchShowList: [
      {
        id: "levelName",
        type: "input",
        width: 30,
        label: "层级名称",
        value: "",
      },
      {
        id: "levelCode",
        type: "input",
        width: 30,
        label: "层级代码",
        value: "",
      },
    ],
    searchParams: {
      current: 1,
      size: 10,
    },

    isShowTable: false,
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "层级名称",
        value: "levelName",
      },
      {
        type: "text",
        label: "层级代码",
        value: "levelCode",
      },
      {
        type: "text",
        label: "层级序列",
        value: "sort",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 180,
        showBtnList: [
          {
            label: "添加下级",
            option: "rowAdd",
          },
        ],
        hideBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },
          {
            label: "删除",
            option: "rowDelete",
          },
        ],
      },
    ],
    tableData: [],
    totalNum: 0,

    currentHandle: null,
  }),

  async mounted() {
    await this.getListHandle();
  },
  methods: {
    async getSelectHandle() {
      try {
        const [{ ["PC-LEVEL-CODE"]: levelCode }, { data: level }] =
          await Promise.all([
            this.$fetchEnumData([enumData.levelCode]),
            getLevel(),
          ]);

        const filterLevelCode = levelCode.map(({ value }) => ({
          label: value,
          value: value,
        }));

        this.updatePopupList("levelCode", { list: filterLevelCode });
        this.updatePopupList("parentId", {
          list: level.data.map(({ levelName, id, sort }) => ({
            label: levelName,
            value: id,
            sort,
          })),
        });
      } catch (error) {
        console.error("获取选择数据失败:", error);
        this.$message.error("获取选择数据失败,请重试");
      }
    },
    updatePopupList(id, updates) {
      const index = this.popupList.findIndex((item) => item.id === id);
      if (index !== -1) {
        this.$set(this.popupList, index, {
          ...this.popupList[index],
          ...updates,
        });
      }
    },
    async operateHandle(val, type) {
      if (type !== "rowDelete") {
        await this.getSelectHandle();
      }

      this.currentHandle = type;
      this.formData = {};

      const parentLevel = this.popupList.find((ele) => ele.id === "parentId");
      parentLevel.disabled = type === "rowEdit";

      const actions = {
        add: () => {
          this.formData = { isIsolation: 0, sort: 1 };
          this.isShowEdit = true;
        },
        rowEdit: () => {
          this.formData = val;
          this.isShowEdit = true;
        },
        rowAdd: () => {
          this.formData = {
            isIsolation: 0,
            parentId: val.id,
            sort: val.sort + 1,
          };
          this.isShowEdit = true;
        },
        rowDelete: async () => {
          const content = val.hasChildren
            ? [`将删除层级${val.sort}及底下所有层级，是否确认删除？`]
            : [this.$t("tip.deleteLevel")];
          const result = await this.$textShow({
            title: this.$t("tip.label"),
            content,
          });
          if (result) await this.removeHandle(val);
        },
      };

      const action = actions[type];
      if (action) action();
    },
    async getListHandle() {
      this.isShowTable = false;

      this.tableData = [];

      const { data } = await getList(this.searchParams);

      this.isShowTable = false;

      this.$validateData(data.data.records);

      this.totalNum = data.data.total;

      this.tableData = data.data.records;
    },
    searchHandle() {
      this.searchParams.current = 1;

      this.getListHandle();
    },
    async confrimHandle() {
      const { currentHandle, formObj, formData } = this;
      let apiCall;

      if (currentHandle === "add" || currentHandle === "rowAdd") {
        apiCall = () => add(formObj);
      } else if (currentHandle === "rowEdit") {
        const updatedFormObj = {
          id: formData.id,
          isIsolation: formObj.isIsolation,
          levelName: formObj.levelName,
          levelCode: formObj.levelCode,
          sort: formObj.sort,
        };
        apiCall = () => update(updatedFormObj);
      }

      if (apiCall) {
        const { data } = await apiCall();
        if (data.code === 200) {
          this.isShowEdit = false;
          this.$message.success(this.$t("msg.success"));
          this.searchParams.current = 1;
          await this.getListHandle();
        }
      }
    },
    selectChange(val) {
      if (val.id === "parentId") {
        const currentParent = val.list.find((item) => item.value === val.value);

        this.$refs.editPopup.outReset("sort", currentParent.sort + 1);
      }
    },
    async removeHandle(val) {
      try {
        const { data } = await remove(val.id);
        if (data.code === 200) {
          this.$message.success(this.$t("msg.success"));
          this.searchParams.current = 1;
          await this.getListHandle();
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    },
    loadFun(tree, treeNode, resolve) {
      getChild(tree.id).then((res) => {
        if (!res.data.data.length) {
          this.$refs.trTable.clearLazyNode(tree.id);
        } else {
          resolve(res.data.data);
        }
      });
    },
  },
};
</script>
